package com.whxy02.tolearn.app.controller;

import com.whxy02.tolearn.app.beans.User;
import com.whxy02.tolearn.app.resultObject.ResultState;
import com.whxy02.tolearn.app.service.UserService;
import com.whxy02.tolearn.app.utils.Md5Util;
import com.whxy02.tolearn.app.utils.PackResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 注册
 */
@RestController
@RequestMapping("/register")
public class Register {

    @Resource
    UserService userService;

    @Resource
    PackResult packResult;

    @Resource
    Md5Util md5Util;

    @RequestMapping("/check")
    public Object check(@RequestParam("username")String username, @RequestParam("pwd")String pwd, @RequestParam("password")String password, @RequestParam("email")String email, HttpServletRequest request, HttpServletResponse response){
        try {
        User u= userService.getByName(username);
        if(u!=null){
            return packResult.doPackToMap(ResultState.USER_HAS_EXIST);
        }
        else if(!password.equals(pwd)){
            return packResult.doPackToMap(ResultState.PASSWORD_NOT_SAME);
        }
        else if(!username.matches("\\w{3,20}")){
            return packResult.doPackToMap(ResultState.USERNAME_ILLEGAL);
        }
        else if(!pwd.matches("\\w{6,20}")){
            return packResult.doPackToMap(ResultState.PASSWORD_ILLEGAL);
        }
        else{
            User user=new User();
            user.setUsername(username);
            user.setPwd(md5Util.md5(pwd));
            user.setEmail(email);
            userService.save(user);
            /**
             * 验证通过并成功注册后跳转至登录页面
             * 暂时不使用
             */
//            response.sendRedirect(request.getContextPath()+"/login.html");
            return packResult.doPackToMap(ResultState.SUCCESS);
            }
        }

        catch (Exception e) {
            return packResult.doPackToMap(ResultState.SERVER_ERR,e);
        }
    }
}
